import { Result, ThemeMode } from '@shared/types.d';
import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';

import { getTheme, setTheme as setMainTheme } from '@/api/system/app';

// 主题色彩类型
export type ThemeColor =
  | 'blue'
  | 'purple'
  | 'green'
  | 'red'
  | 'orange'
  | 'pink'
  | 'cyan'
  | 'indigo'
  | 'emerald'
  | 'rose';

// 主题色彩配置
export const themeColors = [
  { name: '蓝色', value: 'blue', color: '#409EFF' }, // hsl(210, 100%, 63%) -> #409EFF
  { name: '紫色', value: 'purple', color: '#7c3bed' }, // hsl(262, 83%, 58%) -> #7c3bed
  { name: '绿色', value: 'green', color: '#16a249' }, // hsl(142, 76%, 36%) -> #16a249
  { name: '红色', value: 'red', color: '#ef4343' }, // hsl(0, 84%, 60%) -> #ef4343
  { name: '橙色', value: 'orange', color: '#f97415' }, // hsl(25, 95%, 53%) -> #f97415
  { name: '粉色', value: 'pink', color: '#ec4699' }, // hsl(330, 81%, 60%) -> #ec4699
  { name: '青色', value: 'cyan', color: '#0da2e7' }, // hsl(199, 89%, 48%) -> #0da2e7
  { name: '靛青', value: 'indigo', color: '#6467f2' }, // hsl(239, 84%, 67%) -> #6467f2
  { name: '翠绿', value: 'emerald', color: '#10b77f' }, // hsl(160, 84%, 39%) -> #10b77f
  { name: '玫瑰', value: 'rose', color: '#dd1d4a' } // hsl(346, 77%, 49%) -> #dd1d4a
] as const;

export const useThemeStore = defineStore(
  'theme',
  () => {
    // 使用纯 Vue 响应式变量替代 useDark
    const isDark = ref(false);

    // 当前主题模式
    const currentTheme = ref<ThemeMode>(ThemeMode.auto);

    // 当前主题色彩
    const currentThemeColor = ref<ThemeColor>('blue');

    // 计算实际显示的主题
    const actualTheme = computed(() => {
      if (currentTheme.value === ThemeMode.auto) {
        return isDark.value ? ThemeMode.dark : ThemeMode.light;
      }
      return currentTheme.value;
    });

    // 应用主题到 DOM
    const applyTheme = (dark: boolean) => {
      const html = document.documentElement;
      if (dark) {
        html.classList.add('dark');
      } else {
        html.classList.remove('dark');
      }
    };

    // 应用主题色彩到 DOM
    const applyThemeColor = (color: ThemeColor) => {
      const html = document.documentElement;

      // 移除所有主题色彩类
      themeColors.forEach((theme) => {
        html.classList.remove(`theme-${theme.value}`);
      });

      // 添加新的主题色彩类（包括蓝色）
      html.classList.add(`theme-${color}`);
    };

    // 设置主题色彩
    const setThemeColor = (color: ThemeColor) => {
      currentThemeColor.value = color;
      applyThemeColor(color);
    };

    // 设置主题
    const setTheme = async (theme: ThemeMode) => {
      currentTheme.value = theme;

      switch (theme) {
        case ThemeMode.light: {
          isDark.value = false;
          applyTheme(false);
          break;
        }
        case ThemeMode.dark: {
          isDark.value = true;
          applyTheme(true);
          break;
        }
        case ThemeMode.auto: {
          // 跟随系统设置
          const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
          isDark.value = mediaQuery.matches;
          applyTheme(mediaQuery.matches);
          break;
        }
      }

      // 同步到主进程
      try {
        await setMainTheme(theme);
      } catch (error) {
        console.error('Failed to sync theme to main process:', error);
      }
    };

    // 切换亮色/暗色主题
    const toggleTheme = async () => {
      if (currentTheme.value === ThemeMode.auto) {
        // 如果当前是自动模式，切换到相反的固定模式
        await setTheme(isDark.value ? ThemeMode.light : ThemeMode.dark);
      } else {
        // 在亮色和暗色之间切换
        await setTheme(currentTheme.value === ThemeMode.light ? ThemeMode.dark : ThemeMode.light);
      }
    };

    // 监听系统主题变化（仅在 auto 模式下）
    watch(
      () => currentTheme.value,
      (newTheme) => {
        if (newTheme === ThemeMode.auto) {
          const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
          const handleChange = (e: MediaQueryListEvent) => {
            isDark.value = e.matches;
            applyTheme(e.matches);
          };
          mediaQuery.addEventListener('change', handleChange);

          // 清理函数
          return () => {
            mediaQuery.removeEventListener('change', handleChange);
          };
        }
        return undefined;
      },
      { immediate: true }
    );

    // 初始化主题
    const initTheme = async () => {
      const theme = (await getTheme()) as Result<ThemeMode>;
      if (theme.success) {
        await setTheme(theme.data as ThemeMode);
      } else {
        await setTheme(ThemeMode.auto);
      }

      // 应用保存的主题色彩
      applyThemeColor(currentThemeColor.value);
    };

    return {
      isDark,
      currentTheme,
      currentThemeColor,
      actualTheme,
      setTheme,
      setThemeColor,
      toggleTheme,
      initTheme
    };
  },
  {
    persist: {
      key: 'theme-store',
      storage: localStorage
    }
  }
);
